<?php
/**
 * 
 * 
 */	
class Module_ReceiveController extends  Zend_Controller_Action {
	public function init() {
        $app = Zend_Registry::get('App');
        $this->view->baseUrl = $baseUrl = $this->_request->getBaseUrl() . "/public/";
        $result = array(
                    array($baseUrl.'lib-js/module/Module_Receive.js','js')
                    ,array($baseUrl.'css/themes/blitzer/jquery-ui-1.8.14.custom.css','css')
                    ,array($baseUrl.'css/themes/base/calendar.css','css')                    
                    ,array($baseUrl.'lib-js/ui/jquery.ui.datepicker-vi.js','js')
                    ,array($baseUrl.'lib-js/system/upload/css/bootstrap.css','css')
                    ,array($baseUrl.'lib-js/system/upload/css/jquery.fileupload.css','css')
                    ,array($baseUrl.'lib-js/system/upload/css/jquery.fileupload-ui.css','css')
                    ,array($baseUrl.'lib-js/system/upload/js/vendor/jquery.ui.widget.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/tmpl.min.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.iframe-transport.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload-process.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload-ui.js','js')

                );                  
        if ($this->_request->isXmlHttpRequest()){
            Zend_Layout::startMvc(array(
                'layoutPath' => $app->layout,
                'layout' => 'partial'
            ));
            $this->view->arrJsCss = Zend_Json::encode($result);
        }else{
            //Cau hinh cho Zend_layout
            Zend_Layout::startMvc(array(
                'layoutPath' => $app->layout,
                'layout' => 'index'
            ));
            $response = $this->getResponse();
            $this->view->currentModulCode = $this->_request->getParam('controller');
            $this->view->currentModulCodeForLeft = $this->_request->getParam('action');
            $this->view->postHeader = Clound_String::registerFile($result);
            //Hien thi file template
            $response->insert('menu', $this->view->renderLayout('menu.phtml', './application/layout/scripts/'));
            $response->insert('submenu', $this->view->renderLayout('submenu.phtml', './application/layout/scripts/'));
            $response->insert('footer', $this->view->renderLayout('footer.phtml', './application/layout/scripts/'));
        }
    }

    // Xu ly thong tin de day ra file index.phtml
    public function indexAction() {

       // $auth = Zend_Auth::getInstance()->getIdentity()->StaffID;
       // $sesion = Clound_Session::getInstance()->getStaffsHandle();
        // $staffsAssign = Clound_Session::getInstance()->getStaffsAssign();
        // var_dump($staffsAssign);

      /* $model = new System_Models_Permission();
        $out = $model->getPermissionAssign();*/
    }

    public function dataAction(){
        $model = new Module_Models_DocReceive();
        $parames = $this->_request->getParams();
        $parames['Status'] = '';
        $data = $model->getAll($parames);
        $rows = $data[0]['Rows'];
        $iCount = sizeof($rows);
        if ($iCount) {
            $oCacheFile = new Clound_CacheFile();
            $oFile = new Clound_File(null,false);
            $arrDocType = $oCacheFile->getList('DM04');
            for ($i=0; $i < $iCount; $i++) { 
                $rows[$i]['DocType']        = Clound_Public::getNameByCode($arrDocType, $rows[$i]['DocType']);
                $rows[$i]['ReceivedDate']   = date('d/m/Y',strtotime($rows[$i]['ReceivedDate']));
                $rows[$i]['SendDate']       = date('d/m/Y',strtotime($rows[$i]['SendDate']));
                $rows[$i]['Subject']        = $oFile->SumContenAndFile('Subject','ReceiveID','docreceive','RECEIVE',$rows[$i],'FileNames','FileID');
                // $rows[$i]['Subject'] = $rows[$i]['Subject'].'<br>'.$rows[$i]['Subject'].'<br>'.$rows[$i]['Subject'];
                if ($rows[$i]['LocalProcess']) {
                    $local = $xlchinh = $phxl = '';
                    $staffprs = explode('$$', $rows[$i]['LocalProcess']);
                    foreach ($staffprs as $key => $value) {
                        $arr = explode('#', $value);
                        if($arr[1] =='CHINH') $xlchinh .= $arr[0].', ';
                        else $phxl .= $arr[0].', ';
                    }
                    $xlchinh = substr($xlchinh, 0,strlen($xlchinh)-2);
                    $phxl    = substr($phxl, 0,strlen($phxl)-2);
                    if($xlchinh) $local = $xlchinh.' xử lý chính';
                    if($phxl) $local .= '<br>'.$phxl.' phối hợp xử lý';
                    $rows[$i]['LocalProcess'] = $local;
                }
            }
            $data[0]['Rows'] = $rows;
        }

        // var_dump($data[0]['Rows']); die;
        echo Zend_Json::encode($data);
        die;
    }

    /**
     * @see : Thuc hien them/sua van ban den
     *
     */
    public function addAction() {
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
		$this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $iReceiveID = $this->_request->getParam('ReceiveID');
        //Gan gia tri mac dinh cho cac Input
        $model = new Module_Models_DocReceive();
        $model = $model->selectRow($iReceiveID);
        // File xml mô tả form
        $filexml = 'xml/module/receive/_formfield.xml';
        $xmlObj = new Clound_Xml($filexml,$model);
        $formObj = $xmlObj->formfieldGenerate();
        $this->view->form=$formObj;
    }
	/**
     * @see : Thuc hien luu van ban den
     *
     */
    public function saveAction() {
        // Tao doi tuong modeListType
        $model = new Module_Models_DocReceive();
        $oCacheFile = new Clound_CacheFile();
        $oDate = new Clound_Datetime();
        $autoIncement = new Module_Models_Increment();
        $iReceiveID = $this->_request->getParam('ReceiveID',null);
        // $arrPerType = $oCacheFile->getList('DM15');
        $type = 'VBDEN';
        $sAgentcyCode = $this->_request->getParam('AgentcyCode');
        $year = $this->_request->getParam('Year');
        $receiveDate = $oDate->convertDateTime($this->_request->getParam('ReceivedDate'));
        $data = array(
            "ReceiveID" => $iReceiveID,
            "ReceivedDate" => $receiveDate,
            "Year"      => $year,
            "DocType"   => $this->_request->getParam('DocType'),
            "Number"    => $this->_request->getParam('Number'),
            "Symbol"    => $this->_request->getParam('Symbol'),
            "SendDate"  => $oDate->convertDateTime($this->_request->getParam('SendDate')),
            "AgentcyCode"   => $sAgentcyCode,
            "Subject"   =>trim(htmlspecialchars($this->_request->getParam('Subject'))),
            "Emergency" =>$this->_request->getParam('Emergency'),
            "Nature"    =>$this->_request->getParam('Nature'),
        );
        $errors = array();
        if ($iReceiveID) {
            // Sua
            $where="ReceiveID ='$iReceiveID'";
            $model->update($data,$where);
            $increment = $autoIncement->getNumber($year,$type);
            if($increment <= $data['Number']){
                $arrInput = array(
                        'Number'=>(int)$data['Number'] + 1
                    );
                $autoIncement->update($arrInput,"Type='$type' And Years='$year'");
            }            
        } else {
            $data['ReceiveID']= null;
            $data['Number'] = $autoIncement->getNumber($year,$type);
            $data['Status'] = '070002';
            $iReceiveID = $model->insert($data);
            if($iReceiveID){
                // Chuyen lanh dao phan cong
                $staffsAssign = Clound_Session::getInstance()->getStaffsAssign();
				/*
                $arrInputDepartment = array(
                                'DocID'         => $iReceiveID,
                                'DepartmentID'  => $staffsAssign['0']['UnitID'],
                                'Name'          => $staffsAssign['0']['UnitName'],
                                'Role'          => 'LD_PB_PCXL',
                                'ReceiveDate'   => $receiveDate,
                                'Status'        => $data['Status'],
                            );
                $modelDepartment = new Module_Models_ReceiveDepartment();
                $modelDepartment->insert($arrInputDepartment);*/
                // Cap nhat can bo phan cong xu ly
                $arrInputStaff = array(
                                'DocID'         => $iReceiveID,
                                'DepartmentID'  => $staffsAssign['0']['UnitID'],
                                'StaffID'       => $staffsAssign['0']['StaffID'],
                                'PositionName'  => $staffsAssign['0']['Name'],
                                'Role'          => 'LD_PB_PCXL',
                                'ReceiveDate'   => $receiveDate,
                                'Status'        => $data['Status'],
                            );
                $modelStaff = new Module_Models_ReceiveStaff();
                $modelStaff->insert($arrInputStaff);
                // Cap nhat tien do
                $currentStaff = Zend_Auth::getInstance()->getIdentity();
                $arrInputWork = array(
                                'WorkID'        => null,
                                'DocID'         => $iReceiveID,
                                'StaffID'       => $currentStaff->StaffID,
                                'PositionName'  => $currentStaff->Name,
                                'DepartmentID'  => $currentStaff->UnitID,
                                'WorkType'      => '080001',
                                'WorkDate'      => date('Y/m/d H:i:s'),
                                'Result'        => 'Vào sổ văn bản đến',
                    );
                $modelWorkReceive = new Module_Models_WorkReceive();
                $modelWorkReceive->insert($arrInputWork);
            }
        }
        if(empty($errors)){
            $fileObj = new Clound_File(null,false);
            $modelFile = new System_Models_File();
			$arrSign = $model->selectRow($iReceiveID);				
			$sFileIdList = $arrSign['FileID'];
			$sFileNameList = $arrSign['FileNames'];
			//Xoa file
			$sDeleteFileList = $this->_request->getParam('deleteFileList');
			if ($sDeleteFileList != '') {
				$arrFileIdList = explode(',', $sFileIdList);
				$arrFileNameList = explode('!#!', $sFileNameList);			
				$arrDeleteFile = explode('!#~$|*', $sDeleteFileList);
				$count = sizeof($arrDeleteFile);
				for ($i = 0; $i < $count; $i++) {
					$arrTemp = explode('.', $arrDeleteFile[$i]);
					$arrFile = $modelFile->getFileView($arrTemp);
					$delete = $modelFile->deleteRows($arrFile['FileID']);
					$fileObj->_deleteFileAttach($arrFile['FileName']);
					$arrFileIdList = array_diff($arrFileIdList, array($arrFile['FileID']));
					$arrFileNameList = array_diff($arrFileNameList, array($arrFile['FileName']));
				}
				$sFileIdList = implode(',',$arrFileIdList);
				$sFileNameList = implode('!#!', $arrFileNameList);				
			}
            //File dinh kem
            $sAttachfile = $this->_request->getParam('attachfile');
            $arrFileNameList = array();
            if ($sAttachfile != '') {
                $arrFileNameList = $fileObj->_uploadFileAttachList($sAttachfile);
            }
            $count = sizeof($arrFileNameList);
            if($count){
                for ($i = 0; $i < $count; $i++) {
                    $sFileId = '';
                    //Mang gia tri
                    $data = array(
                        "FileID"            =>  0,
                        "RecordID"          =>  $iReceiveID,
                        "RecordType"        =>  'RECEIVE',
                        "FileType"          =>  strtolower(pathinfo($arrFileNameList[$i], PATHINFO_EXTENSION)),
                        "FileName"          =>  $arrFileNameList[$i],
                        "TableName"         =>  'docreceive'
                    );
                    $modelFile->insert($data);
                    $sFileId = $modelFile->getAdapter()->lastInsertId();
                    if($sFileIdList==''){
                        $sFileIdList = $sFileId;
                        $sFileNameList = $arrFileNameList[$i];
                    }else{
                        $sFileIdList .= ','.$sFileId;
                        $sFileNameList .= '!#!'.$arrFileNameList[$i];
                    }
                }
            }
			//Update file id
			$data = array(
						"ReceiveID"     =>  $iReceiveID,
						"FileID"        =>  $sFileIdList,
						"FileNames"      =>  $sFileNameList
					);
			$where="ReceiveID ='$iReceiveID'";
			$model->update($data,$where);			
        }
        // echo $model->getAdapter()->lastInsertId();
        echo Zend_Json::encode($errors);
        die;
        $this->_helper->getHelper('viewRenderer')->setNoRender();
    }
    /**
     * @see : Thuc hien viec xoa Mot hoac Nhieu van ban den
     */
    public function deleteAction() {
        $model = new Module_Models_DocReceive;
        $sReceiveIDList = $this->_request->getParam('ReceiveIDs');
        echo Zend_Json::encode($model->deleteRows($sReceiveIDList));
        die();
    }

    /**
     * @see : Cho phan cong
     */
    public function assignwaitAction() {
        
    }

    /**
     * @see : Phan cong
     */
    public function assignAction() {
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
        $this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $iReceiveID = $this->_request->getParam('ReceiveID');
        //Gan gia tri mac dinh cho cac Input
        $model = new Module_Models_DocReceive();
        $model = $model->selectRow($iReceiveID);
        // File xml mô tả form
        $filexml = 'xml/module/receive/assign.xml';
        $data = array(
                        'ReceivedDate'=>date('d/m/Y')
                        ,'ReceiveID'=>$iReceiveID
                    );
		//Lay can bo co quyen xu ly vb
		$session = new Clound_Session();
		$iStaff = Zend_Auth::getInstance()->getIdentity()->StaffID;
		$session->getsetStaffsByPermission('160004',false,$iStaff);			
        $xmlObj = new Clound_Xml($filexml,$data);
        $formObj = $xmlObj->formfieldGenerate();
        $this->view->form=$formObj;
    }
    /**
     * @see : Cap nhat phan cong xu ly
     *
     */
    public function saveassignAction() {
        // Tao doi tuong modeListType
        $model = new Module_Models_DocReceive();
        $oCloundPublic = new Clound_Public();
        $oDate = new Clound_Datetime();
        $iReceiveID = $this->_request->getParam('ReceiveID',null);
        $staffkeyhandle = $this->_request->getParam('staffkeyhandle',null);
        $Staffcoordinatedhandle = $this->_request->getParam('Staffcoordinatedhandle',null);
        $idea = $this->_request->getParam('Idea',null);

        $receiveDate = $oDate->convertDateTime($this->_request->getParam('ReceivedDate'));
        $appointedDate = $oDate->convertDateTime($this->_request->getParam('AppointedDate'));
        $data = array(
            "ReceiveID" => $iReceiveID,
            "Status"      => '070004'
        );

        $errors = array();
        
        if($iReceiveID){
            $staff = $oCloundPublic->getDepFromStaff($staffkeyhandle);
            $localProcess = $staff['Name'].'#CHINH';
            // Cap nhat thong tin can bo xu ly
            $arrInputStaff = array(
                            'DocID'         => $iReceiveID,
                            'DepartmentID'  => $staff['UnitID'],
                            'StaffID'       => $staff['StaffID'],
                            'PositionName'  => $staff['Name'],
                            'Role'          => 'XL_CHINH',
                            'ReceiveDate'   => $receiveDate,
                            'AppointedDate' => $appointedDate,
                            'Idea'          => $idea,
                            'Status'        => $data['Status'],
                        );
            $modelStaff = new Module_Models_ReceiveStaff();
            $modelStaff->insert($arrInputStaff);
            // Cap nhat can bo phoi hop xu ly
            if($Staffcoordinatedhandle){
                foreach ($Staffcoordinatedhandle as $key => $value) {
                    $staff = $oCloundPublic->getDepFromStaff($value);
                    $arrInputStaff = array(
                            'DocID'         => $iReceiveID,
                            'DepartmentID'  => $staff['UnitID'],
                            'StaffID'       => $staff['StaffID'],
                            'PositionName'  => $staff['Name'],
                            'Role'          => 'PHOI_HOP_XL',
                            'ReceiveDate'   => $receiveDate,
                            'AppointedDate' => $appointedDate,
                            'Idea'          => $idea,
                            'Status'        => $data['Status'],
                        );
                    $localProcess .= '$$'.$staff['Name'].'#PH';
                    $modelStaff->insert($arrInputStaff);
                }
            }
            $StaffID = Zend_Auth::getInstance()->getIdentity()->StaffID;
            $modelStaff->update(array('Status'=>'070005','Idea'=>$idea),"DocID ='$iReceiveID' And StaffID='$StaffID'");
            // LocalProcess
            $data['LocalProcess'] = $localProcess;
            $model->update($data,"ReceiveID ='$iReceiveID'");
        }
        
        echo Zend_Json::encode($errors);
        die;
        $this->_helper->getHelper('viewRenderer')->setNoRender();
    }
    /**
     * @see : Cho phan cong
     */
    public function dataassignwaitAction() {
        $model = new Module_Models_DocReceive();
        $parames = $this->_request->getParams();
        $parames['Status'] = '070002';
        $data = $model->getassign($parames);
        $rows = $data[0]['Rows'];
        $iCount = sizeof($rows);
        if ($iCount) {
            $oCacheFile = new Clound_CacheFile();
            $oFile = new Clound_File(null,false);
            $arrDocType = $oCacheFile->getList('DM04');
            for ($i=0; $i < $iCount; $i++) { 
                $rows[$i]['DocType']        = Clound_Public::getNameByCode($arrDocType, $rows[$i]['DocType']);
                $rows[$i]['ReceivedDate']   = date('d/m/Y',strtotime($rows[$i]['ReceivedDate']));
                $rows[$i]['SendDate']       = date('d/m/Y',strtotime($rows[$i]['SendDate']));
                $rows[$i]['Subject']        = $oFile->SumContenAndFile('Subject','ReceiveID','docreceive','RECEIVE',$rows[$i],'FileNames','FileID');
                
            }
            $data[0]['Rows'] = $rows;
        }
        // var_dump($data[0]['Rows']); die;
        echo Zend_Json::encode($data);
        die;
    }
    /**
     * @see : Da phan cong
     */
    public function assignedAction() {
        
    }

    /**
     * @see : Da phan cong
     */
    public function dataassignedAction() {
        $model = new Module_Models_DocReceive();
        $parames = $this->_request->getParams();
        $parames['Status'] = '070005';
        
        $data = $model->getassign($parames);
        $rows = $data[0]['Rows'];
        $iCount = sizeof($rows);
        if ($iCount) {
            $oCacheFile = new Clound_CacheFile();
            $oFile = new Clound_File(null,false);
            $arrDocType = $oCacheFile->getList('DM04');
            for ($i=0; $i < $iCount; $i++) { 
                $rows[$i]['DocType']        = Clound_Public::getNameByCode($arrDocType, $rows[$i]['DocType']);
                $rows[$i]['ReceivedDate']   = date('d/m/Y',strtotime($rows[$i]['ReceivedDate']));
                $rows[$i]['SendDate']       = date('d/m/Y',strtotime($rows[$i]['SendDate']));
                $rows[$i]['Subject']        = $oFile->SumContenAndFile('Subject','ReceiveID','docreceive','RECEIVE',$rows[$i],'FileNames','FileID');
                
            }
            $data[0]['Rows'] = $rows;
        }
        // var_dump($data[0]['Rows']); die;
        echo Zend_Json::encode($data);
        die;
    }
}?>
